﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using LView.CMS.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using NLog;
using LView.CMS.IServices;

namespace LView.CMS.Site.Filter
{
    /// <summary>
    /// 异步全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        //public static Logger logger = LogManager.GetCurrentClassLogger();

        //public void OnException(ExceptionContext filterContext)
        //{
        //    logger.Error(filterContext.Exception);
        //    var result = new BaseResult()
        //    {
        //        ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode,
        //        ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg
        //    };
        //    filterContext.Result = new ObjectResult(result);
        //    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        //    filterContext.ExceptionHandled = true;
        //}
        private readonly INlogHelperService _logHelper;

        public GlobalExceptionFilter(INlogHelperService logHelper)
        {
            _logHelper = logHelper;
        }

        /// <summary>
        /// 重新OnExceptionAsync方法
        /// </summary>
        /// <param name="context">异常信息</param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理，则进行处理
            if (context.ExceptionHandled == false)
            {
                // 记录错误信息
                _logHelper.LogError(context.Exception);
                // 设置为true，表示异常已经被处理了，其它捕获异常的地方就不会再处理了
                context.ExceptionHandled = true;
            }

            return Task.CompletedTask;
        }
    }
}
